const jwt = require('jsonwebtoken');

const secretKey = 'irelib';
const signOptions = {
	expiresIn: '5h',
};
const verifyOptions = {};

const useJwt = {
	sign: (payload, secret = secretKey, options = signOptions) => {
		return jwt.sign(payload, secret, options);
	},
	verify: (token, secret = secretKey, options = verifyOptions) => {
		let verify = false;
		jwt.verify(token, secret, options, (err, decoded) => {
			verify = !err;
			if (err) {
				verify = false;
			} else {
				verify = decoded;
			}
		});
		return verify;
	},
};

// token验证中间件
async function verifyRouter(ctx, next) {
	let authorization = ctx.headers.authorization || '';
	authorization = authorization.replace('Bearer ', '');
	const verify = useJwt.verify(authorization);
	if (verify) {
		await next();
	} else {
		ctx.status = 401;
	}
}

module.exports = {
	useJwt,
	verifyRouter,
};
